package GUIClient;

import CommonOperationsClientServer.FilesOperations;
import CommonOperationsClientServer.OperationsRefactor;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JTree;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

public class GUIExtraFunctions {

    public static void updateTextPane(JTextPane panel, String newText) {
        String text = panel.getText() + systemDate() + " " + newText + "\n";
        panel.setText(text);
    }

    public static void updateTextPane(JTextPane panel, BufferedReader input) {
        try {
            updateTextPane(panel, input.readLine());
        } catch (Exception e) {
        }
    }

    private static String systemDate() {
        String date;
        Date fecha = new Date();
        date = fecha.toString();
        return (" (" + date + ")");
    }

    public static String filterPath(TreePath path) {
        String result;
        result = path.toString();
        result = result.replace("[", "");
        result = result.replace("]", "");
        result = result.replaceAll(", ", "/");
        return result;
    }

    public static DefaultTreeModel treeFinal(String directory, boolean isServer, BufferedReader input,
            PrintWriter output) {
        if (!directory.equals("")) {
            DefaultMutableTreeNode father = new DefaultMutableTreeNode(directory);
            removeNodes(father, directory, isServer, input, output);
            JTree tree = new JTree(father);
            DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
            return model;
        } else {
            return null;
        }
    }

    private static ArrayList<String> createArrayListFromServer(String filePath, BufferedReader input,
            PrintWriter output) {
        ArrayList<String> list = new ArrayList<>();
        OperationsRefactor.outputMessage(output, "listdirectoryserver;" + filePath);
        String line;
        try {
            //@Abraham ojo que readLine devuelve null si hay un fallo
            while (!(line = input.readLine()).equals("listOfDirectoriesEnd")) {
                list.add(line);
            }
        } catch (Exception e) {
        }
        return list;
    }

    private static ArrayList<String> createArrayList(String filePath) {
        ArrayList<String> list = new ArrayList<>();
        File f = new File(filePath);
        File[] fileList = f.listFiles(new FileFilter() {

            @Override
            public boolean accept(File pathname) {
                return true;
            }
        });
        if (fileList != null) {
            for (int i = 0; i < fileList.length; i++) {
                list.add(fileList[i].toString());
            }
        }
        return list;
    }

    private static boolean removeNodes(DefaultMutableTreeNode node, String directoryPath, boolean isServer,
            BufferedReader input, PrintWriter output) {
        node.removeAllChildren();
        return removeNodes(node, directoryPath, 2, isServer, input, output);
    }

    private static boolean removeNodes(DefaultMutableTreeNode node, String directoryPath, int index,
            boolean isServer, BufferedReader input, PrintWriter output) {
        ArrayList<String> list;
        if (isServer) {
            list = createArrayListFromServer(directoryPath, input, output);
        } else {
            list = createArrayList(directoryPath);
        }
        if (index > 0) {
            for (int i = 0; i < list.size(); i++) {
                DefaultMutableTreeNode children = new DefaultMutableTreeNode(list.get(i));
                removeNodes(children, list.get(i), index - 1, isServer, input, output);
                node.add(children);
            }
        }
        return true;
    }

    public static boolean treeExpanded(TreeExpansionEvent evt, boolean isServer, BufferedReader input,
            PrintWriter output) {
        TreePath directory = evt.getPath();
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) directory.getLastPathComponent();
        if (node == null) {
            return true;
        }
        removeNodes(node, (String) node.getUserObject(), isServer, input, output);
        JTree tree = (JTree) evt.getSource();
        DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
        model.nodeStructureChanged(node);
        return false;
    }

    public static String treeValueChanged(TreeSelectionEvent evt, JTextField dateText, JTextField size,
            JTextField type, JTextField permissions, JTextField visibility, BufferedReader input,
            PrintWriter output, boolean isServer) {
        TreePath directory = evt.getPath();
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) directory.getLastPathComponent();
        if (node == null) {
            return null;
        }
        String stringPermissions;
        if (isServer) {
            stringPermissions = "";
            OperationsRefactor.outputMessage(output, "filepermissions;" + node.toString());
            try {
                stringPermissions = input.readLine();
            } catch (Exception e) {
            }
        } else {
            stringPermissions = FilesOperations.getInfoFromLocalFile(node.toString());
        }
        if (!stringPermissions.equals("null")) {
            String[] filePermissions = stringPermissions.split(";");
            dateText.setText(filePermissions[0]);
            size.setText(filePermissions[1]);
            type.setText(filePermissions[2]);
            permissions.setText(filePermissions[3]);
            visibility.setText(filePermissions[4]);
        }
        return node.toString();
    }

    public static void updatePanel(JTextPane localPane, JTextPane serverPane, String message) {
        GUIExtraFunctions.updateTextPane(localPane, message);
        GUIExtraFunctions.updateTextPane(serverPane, message);
    }

    public static void updatePanel(JTextPane localPane, JTextPane serverPane, String localMessage,
            String serverMessage) {
        GUIExtraFunctions.updateTextPane(localPane, localMessage);
        GUIExtraFunctions.updateTextPane(serverPane, serverMessage);
    }
}
